module.exports = function(app) {	
	return {
		"get":function(p_fnsuccess,p_fnerror){
			app.models.perfil.find().exec().then(p_fnsuccess,p_fnerror);
		}
		,"getByIdPerfil":function(p_idPerfil,p_fnsuccess,p_fnerror){
			app.models.perfil.find({"_id":p_idPerfil,"snAtivo":"S"}).exec().then(p_fnsuccess,p_fnerror);
		}
		,"getPerfilSimples":function(p_fnsuccess,p_fnerror){
			app.models.perfil.find({"snAtivo":"S"},{
					"descricao":1
	        		,"comentario":1
	        		,"snAtivo":1
	    		}).exec().then(p_fnsuccess,p_fnerror);
		}		
		,"insert":function(p_perfil,p_fnsuccess,p_fnerror) {		
			app.models.perfil.create(p_perfil).then(
				function(dta){				
					p_fnsuccess(dta._id);
				}
				,p_fnerror
			);
		}
		,"update":function(p_perfil,p_fnsuccess,p_fnerror){
			app.models.perfil.findByIdAndUpdate(p_perfil._id,p_perfil).exec().then(
				function(dta){
					p_fnsuccess(true);
				}
				,p_fnerror
			);
		}
		,"delete":function(p_id,p_fnsuccess,p_fnerror) {
			app.models.perfil.remove({"_id":p_id}).exec().then(
				function(){
					p_fnsuccess(true);
				}
				,p_fnerror
			);
		}
		,"addMenu":function(p_idPerfil,p_menu,p_fnsuccess,p_fnerror) {				
			app.models.perfil.findById(p_idPerfil,function(erro,data){
				if(erro){
					p_fnerror(erro);
				}else{
					var newdoc = data.menus.create(p_menu);
					console.log(newdoc);
					data.menus.push(newdoc);				
					data.save(function (err) {
						if(err){
							return p_fnerror(err);
						};
						console.log('the sub-doc was saved2');
					});
					p_fnsuccess(newdoc._id);				
				};			
			});  
		}
		,"updateMenu":function(p_idPerfil,p_menu,p_fnsuccess,p_fnerror) {	
			app.models.perfil.findOneAndUpdate(
				{ "_id": p_idPerfil , "menus._id": p_menu._id }
				,{ "$set":{"menus.$": p_menu}}
				,function(err,doc) {
					if(err){
						p_fnerror(err);
					}else{
						p_fnsuccess(true);						
					}
				}
			);
		}
		,"deleteMenu":function(p_idPerfil,p_idMenu,p_fnsuccess,p_fnerror) {						
			app.models.perfil.findByIdAndUpdate(p_idPerfil,{$pull:{"menus":{_id:p_idMenu}}}).then(
				function(dta){		
					p_fnsuccess(true);
				}
				,p_fnerror
			);
		}
		,"addMenuItem":function(p_idPerfil,p_idMenu,p_menuItem,p_fnsuccess,p_fnerror) {
			app.models.perfil.find(
				{
	        		"_id":p_idPerfil
	      		}
	    		,{
					"descricao":1
	        		,"menus":1
	    		}
	    		,function(err,rowPerfil){
	    			if(err){
	    				p_fnerror(err);
	    			}else{
	    				rowPerfil.forEach(function(itemPerfil){ 
							//x.menus.find({"_id":ObjectId("559d99fca6c60d58185c0cee")}).children.insert({"label":"agora de novo","ordem":48998}); 
						    //print(x.menus);
						    //print(x);
						    var indNew = 0;
						    var y = 0;
						    var tmMenus = itemPerfil.menus.length;
						    for(y = 0;y < tmMenus;y++){
						        //usando desc, para simplificar, mas em producao sera _id do Menu
						        if(itemPerfil.menus[y]._id==p_idMenu){
						            //itemPerfil.menus[y].children.push({"label":"novo item "+itemPerfil.menus[y].children.length+" para o menu2","ordem":48998});
						            itemPerfil.menus[y].children.push(p_menuItem);
						            indNew = itemPerfil.menus[y].children.length;
						            break;
						        };
						    }; 
						    itemPerfil.save(itemPerfil,function (err2) {
				  				if (err2){
				  					p_fnerror(err2);
				  				}else{
				  					//console.log(itemPerfil.menus[y].children[indNew-1]);
				  					p_fnsuccess(itemPerfil.menus[y].children[indNew-1]._id);
				  				};
				 				//console.log('Success!');
				 				//p_fnsuccess(subdoc._id);	 				
							});
						   	//print(x.menus[0].children);
						    //pegando o novo id inserido
			   				//console.log(itemPerfil.menus[y].children[indNew-1]);
			   				//p_fnsuccess(itemPerfil.menus[y].children[indNew-1]);
						});
	    			};
				}
			);



			/*
			var docMenu = app.models.perfil.id(p_idPerfil).menus.id(p_idMenu);

			docMenu.children.push(p_menuItem);

			var subdoc = docMenu.children[0];
			console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
			subdoc.isNew; // true

			docMenu.save(function (err) {
  				if (err){
  					 return handleError(err);
  				};
 				console.log('Success!');
 				p_fnsuccess(subdoc._id);
			});
			*/
			/*
			app.models.perfil.findOneAndUpdate(
				{ "_id": p_idPerfil , "menus._id": p_idMenu }
				,{"$set":{"menus.0.children": p_menuItem}}
				,{"multi":0,"upsert":1}
				,function(err,doc) {
					if(err){
						p_fnerror(err);
					}else{
						console.log("---------!teste-------");
						console.log(doc.menus[0].children);
						console.log("---------!teste-------");
						p_fnsuccess(true);						
					}
				}
			);
			*/
			/*
			app.models.perfil.findOne(
				{ "_id": p_idPerfil , "menus._id": p_idMenu }
				,function(err,doc) {
					if(err){
						p_fnerror(err);
					}else{
						console.log("---------!teste-------");
						//console.log(doc.menus[0].children);
						console.log(doc);
						console.log("---------!teste-------");
						//p_fnsuccess(true);		

						app.models.perfil.populate(doc,p_menuItem,function(err2,doc2){
							p_fnsuccess(doc2._id);
						});
  						//promise.then(console.log).end();

					}
				}
			);
			*/
			/*
			app.models.perfil.findById(p_idPerfil,function(erro,data){
				if(erro){
					p_fnerror(erro);
				}else{
					data.menus.findById(p_idMenu,function(erro2,data2){
						if(erro2){
							p_fnerror(erro2);
						}else{
							var newdoc = data2.children.create(p_menuItem);
							data2.children.push(newdoc);				
							data2.save(function (err){
								if(err){
									return handleError(err);
								};
								console.log('the sub-doc2 was saved!');
							});
							p_fnsuccess(newdoc._id);
						};
					});				
				};			
			});  
			*/
		}
		,"updateMenuItem":function(p_idPerfil,p_idMenu,p_menuItem,p_fnsuccess,p_fnerror) {	
			//bugado rsrsrs
			/*
			app.models.perfil.findOneAndUpdate(
				{ "_id": p_idPerfil , "menus._id": p_idMenu,"menus.children._id" : p_menuItem._id}
				,{"$set":{"menus.$.children": p_menuItem}}
				,{"multi":0,"upsert":0}
				,function(err,doc) {
					if(err){
						p_fnerror(err);
					}else{
						console.log("---------!teste-------");
						//console.log(doc);
						console.log(doc.menus[0].children);
						console.log("---------!teste-------");
						p_fnsuccess(true);						
					}
				}
			);
			*/

			app.models.perfil.update(
    					{ "menus.children._id" : p_menuItem._id },
    					{ "$push": { "menus.0.children": p_menuItem } },
    							function(err,numAffected) {
      								if(err){
      									p_fnerror(err);
      								}else{
      									console.log(numAffected);
      									p_fnsuccess(true);	
      								};
    							}
						);

			/*
			app.models.perfil.find(
				{
	        		"_id":p_idPerfil
	      		}
	    		,{
					"descricao":1
	        		,"menus":1
	    		}
	    		,function(err,rowPerfil){
	    			if(err){
	    				p_fnerror(err);
	    			}else{
	    				rowPerfil.forEach(function(itemPerfil){ 
							//x.menus.find({"_id":ObjectId("559d99fca6c60d58185c0cee")}).children.insert({"label":"agora de novo","ordem":48998}); 
						    //print(x.menus);
						    //print(x);
						    var indNew = 0;
						    var y = 0;
						    var tmMenus = itemPerfil.menus.length;
						    for(y = 0;y < tmMenus;y++){
						        //usando desc, para simplificar, mas em producao sera _id do Menu
						        if(itemPerfil.menus[y]._id==p_idMenu){
						            //itemPerfil.menus[y].children.push({"label":"novo item "+itemPerfil.menus[y].children.length+" para o menu2","ordem":48998});
						            itemPerfil.menus[y].children.push(p_menuItem);
						            indNew = itemPerfil.menus[y].children.length;
						            break;
						        };
						    }; 
						    itemPerfil.save(itemPerfil,function (err2) {
				  				if (err2){
				  					p_fnerror(err2);
				  				}else{
				  					//console.log(itemPerfil.menus[y].children[indNew-1]);
				  					p_fnsuccess(true);
				  				};
				 				//console.log('Success!');
				 				//p_fnsuccess(subdoc._id);	 				
							});
						   	//print(x.menus[0].children);
						    //pegando o novo id inserido
			   				//console.log(itemPerfil.menus[y].children[indNew-1]);
			   				//p_fnsuccess(itemPerfil.menus[y].children[indNew-1]);
						});
	    			};
				}
			);
			*/
		}
		,"deleteMenuItem":function(p_idPerfil,p_idMenu,p_idMenuItem,p_fnsuccess,p_fnerror) {						
			//bugado eu acho

			app.models.perfil.findByIdAndUpdate(p_idPerfil,{$pull:{"menus":{_id:p_idMenu}}}).then(
				function(dta){		
					p_fnsuccess(true);
				}
				,p_fnerror
			);
		}
	};
};
